import { Component, OnInit } from '@angular/core';
import {Rescatalog} from '../rescatalog';
import {TreeUtil} from '../../../util/tree-util';
import {RescatalogService} from '../rescatalog.service';
import {OneDialogService} from '../../../widgets/one-dialog/one-dialog.service';
import {MsgResult} from '../../../models/msg-result';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {PageSubject} from '../../../util/page-subject';
import {ResponseUtil} from '../../../util/response-util';
import {ActivatedRoute, Router} from '@angular/router';
import {MsgConstants} from '../../../constants/constants';

declare var $;

@Component({
  selector: 'app-rescatalog-update',
  templateUrl: './rescatalog-update.component.html',
  styleUrls: ['./rescatalog-update.component.css']
})
export class RescatalogUpdateComponent implements OnInit {
  rescatalog: Rescatalog;

  rescatalogForm: FormGroup;

  treeObj;
  treeData: Array<any> = [];

  /**
   * 校验字段
   */
  formErrors = {
    'pName': '',
    'resName': '',
    'resCode': '',
    'resValue': '',
    'orderNum': '',
    'describe': '',
    'enName': '',
    'isUse': ''
  };

  /**
   * 校验提示信息
   */
  validationMessages = {
    'pName': {},
    'resName': {
      'required': '名称不能为空',
    },
    'resCode': {
      'required': '编码不能为空',
      'pattern': '只能由大写字母、数字、下划线组成'
    },
    'resValue': {
      'pattern': '必须为字母或数字或空'
    },
    'orderNum': {
      'required': '排序不能为空',
      'pattern': '只能是数字' ,
      'maxlength': '长度不能超过4'
    },
    'describe': {
      'maxlength': '长度不能超过200',
    },
    'enName': {
      'maxlength': '长度不能超过100',
      'required': '英文名称不能为空',
      'pattern': '只能是英文字母'
    },
    'isUse': {},
  };
  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private fb: FormBuilder,
    private treeUtil: TreeUtil,
    private pageSubject: PageSubject,
    private responseUtil: ResponseUtil,
    private dialogService: OneDialogService,
    private rescatalogService: RescatalogService,
  ) {
    this.initObject();
  }

  ngOnInit() {
    this.initResCaTree();
    this.pushPage();
  }

  /**
   * 面包屑导航
   */
  pushPage() {
    // const path = new Path('数据字典','');
    this.pageSubject.pushPage('资源目录', '添加');
  }

  /**
   * 实例化对象
   */
  private initObject() {
    this.rescatalog = new Rescatalog();
    this.buildForm();
  }

  /**
   * 构造表单
   */
  buildForm(): void {
    this.rescatalogForm = this.fb.group({
      'pId': [this.rescatalog.pId],
      'pName': [this.rescatalog.pName],
      'id': [this.rescatalog.id],
      'resName': [this.rescatalog.resName, [
        Validators.required,
      ]],
      'resCode': [this.rescatalog.resCode, [
        Validators.required,
        Validators.pattern(/^[A-Z-0-9_]+$/)
      ]],
      'resValue': [this.rescatalog.resValue, [
        Validators.pattern(/^[A-Za-z0-9_]+$/)
      ]],
      'orderNum': [this.rescatalog.orderNum, [
        Validators.required,
        Validators.maxLength(4),
        Validators.pattern(/^[\d]{0,}$/)
      ]],
      'describe': [this.rescatalog.describe, [
        Validators.maxLength(200)
      ]],
      'isUse': [this.rescatalog.isUse = '1', [
        Validators.maxLength(1)
      ]],
      'enName': [this.rescatalog.enName, [
        Validators.required,
        Validators.pattern(/^[A-Za-z]+$/),
        Validators.maxLength(100)
      ]]

    });

    this.rescatalogForm.valueChanges.subscribe(
      data => this.onValueChanged(data)
    );
    this.onValueChanged();
  }


  /**
   * 值变化监听
   * @param data
   */
  onValueChanged(data?: any) {
    if (!this.rescatalogForm) {
      return;
    }
    const form = this.rescatalogForm;
    for (const field in this.formErrors) {
      this.formErrors[field] = '';
      const control = form.get(field);
      if (control && control.dirty && !control.valid) {
        const messages = this.validationMessages[field];
        for (const key in control.errors) {
          this.formErrors[field] += messages[key] + ' ';
        }
      }
    }
  }

  /**
   * 保存菜单修改信息
   */
  onSubmit() {
    this.rescatalog = this.rescatalogForm.value;
    this.rescatalogService.updateRescatalog(this.rescatalog).subscribe(
      result => this.responseUtil.success(result, this.processDictionaryAddResult),
      message => this.responseUtil.error(message)
    );
  }

  /**
   * 处理修改结果
   * @param result
   */
  private processDictionaryAddResult = (result: MsgResult) => {
    if (result && result.code === MsgConstants.MSG_CODE_OK) {
      // this.rescatalog = result.data;
      this.dialogService.success(result.message);
      this.cancelResCatalogUpdate();
    }
    if (result && result.code !== MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * 取消添加菜单
   */
  cancelResCatalogUpdate() {
    this.router.navigate(['..'], {relativeTo: this.route});
  }

  /**
   * 初始化菜单树
   */
  initResCaTree() {
    this.rescatalogService.getRescatalog().subscribe(
      result => this.responseUtil.success(result, this.processDictionaryTreeResult),
      message => this.responseUtil.error(message)
    );
  }
  private processDictionaryTreeResult = (result: MsgResult) => {
    if (result && result.code === MsgConstants.MSG_CODE_OK) {
      this.treeData = result.data;
      this.initResCaTreeObj(result.data);
      this.initFormData();
    }
    if (result && result.code !== MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  };

  initResCaTreeObj(data) {
    // 初始化菜单树
    const setting = {
      callback: {
        onClick: this.clickTree
      },
      data: {
        key: {
          name: 'resName'
        }
      }

    };
    // 把树放进页面
    this.treeObj = $.fn.zTree.init($('#resCa_add_ZTree'), setting, this.treeUtil.wrapToStandard(data));
  }
  clickTree = (event, treeId, treeNode) => {
    if (this.rescatalog.id === treeNode.id || treeNode.pId === this.rescatalog.id) {
      this.dialogService.info('不能选择当前修改的资源目录及其子目录');
      return false;
    }
    if (treeNode.id === this.rescatalogForm.value.pId) {
      const nodes = this.treeObj.getSelectedNodes();
      if (nodes.length > 0) {
        this.treeObj.cancelSelectedNode(nodes[0]);
      }
      this.rescatalog = this.rescatalogForm.value;
      this.rescatalog.pId = '';
      this.rescatalog.pName = '';
      this.rescatalogForm.patchValue(this.rescatalog);
    } else {
      this.rescatalog = this.rescatalogForm.value;
      this.rescatalog.pId = treeNode.id;
      this.rescatalog.pName = treeNode.resName;
      this.rescatalogForm.patchValue(this.rescatalog);
    }
  };

  /**
   * 初始化数据
   */
  initFormData() {
    const id = this.route.snapshot.params['id'];
    this.rescatalogService.getRescatalogById(id).subscribe(
      result => this.responseUtil.success(result, () => {
        if (result && result.code === MsgConstants.MSG_CODE_OK) {
          if (result.data) {
            this.rescatalog = JSON.parse(JSON.stringify(result.data));
            this.treeData.every((val) => {
              if (val.id === this.rescatalog.pId) {
                this.rescatalog.pName = val.resName;
                return false
              } else {
                return true
              }
            });
            this.rescatalogForm.patchValue(this.rescatalog)
          }
        }
        if (result && result.code !== MsgConstants.MSG_CODE_OK) {
          this.dialogService.info(result.message);
        }
      }),
      error => this.responseUtil.error(error)
    )
  }
}
